<!DOCTYPE html>
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
	<title>Promise testDemo</title>
	<style type="text/css">
	* {
		padding: 0;
		margin: 0;
	}
	
</style>
</head>
<body>
	<h1>aaaa</h1>
</body>
<script src="index.js"></script>
<script type="text/javascript">
class ParamError extends Error {
  constructor(msg) {
    super(msg);
    this.name = "ParamError";
  }
}

class HttpError extends Error {
  constructor(msg) {
    super(msg);
    this.name = "HttpError";
  }
}

function ajax(url) {
	return new Promise((resolve, reject) => {
		if(!/^https?/.test(url)) {
			// throw new ParamError("请求地址格式错误");
			// resolve('hello '+  url)
			reject('请求地址格式错误')
			// return ;
			
		}

		let xhr = new XMLHttpRequest();
	    xhr.open("GET", url);
	    xhr.send();
	    xhr.onload = function() {
	    	if (this.status == 200) {
		        resolve(JSON.parse(this.response));
		      } else if (this.status == 404) {
		        // throw new HttpError("用户不存在");
		        reject(new HttpError("用户不存在"));
		      } else {
		        reject("加载失败");
		      }

	    }
	    xhr.onerror = function() {
	      reject(this);
	    };

	});

}


ajax(`ht3tp://localhost:3010/php/user.php?name=后盾人`)
.then(value => {
  console.log(value);
})
.catch(error => {
  if (error instanceof ParamError) {
    console.log('ParamError', error.message);
  }
  if (error instanceof HttpError) {
    alert('HttpError' + error.message);
  }
  console.warn('其他错误哦', error);
});


</script>
</html>